import React, { useState, useEffect } from 'react';
import { userService } from '../../services/user';
import UserLayout from './UserLayout';
import PaginationComponent from '../network/NetworkHome/components/PaginationComponent.js';
import './Passkey.css';

const Passkey = () => {
  const [currentPasskey, setCurrentPasskey] = useState(null);
  const [passkeyHistory, setPasskeyHistory] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    size: 10,
    total: 0,
  });

  useEffect(() => {
    fetchPasskeyData();
  }, [pagination.current, pagination.size]);

  const fetchPasskeyData = async () => {
    try {
      setLoading(true);
      const [currentResponse, historyResponse] = await Promise.all([
        userService.getCurrentPasskey(),
        userService.getPasskeyHistory({ current: pagination.current, size: pagination.size })
      ]);

      if (currentResponse.data.code === 200) {
        setCurrentPasskey(currentResponse.data.data);
      }

      if (historyResponse.data.code === 200) {
        setPasskeyHistory(historyResponse.data.data.records);
        setPagination(prev => {
          if (prev.total !== historyResponse.data.data.total) {
            return { ...prev, total: historyResponse.data.data.total };
          }
          return prev;
        });
      }
    } catch (err) {
      setError('获取Passkey信息失败');
    } finally {
      setLoading(false);
    }
  };

  const handleGenerateNewPasskey = async () => {
    try {
      setLoading(true);
      const response = await userService.generatePasskey();
      if (response.data.code === 200) {
        setCurrentPasskey(response.data.data);
        setSuccess('新的Passkey已生成');
        // 刷新历史记录
        fetchPasskeyData();
      }
    } catch (err) {
      setError(err.response?.data?.message || '生成新Passkey失败');
    } finally {
      setLoading(false);
    }
  };

  // 分页切换
  const handlePageChange = (page, pageSize) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      size: pageSize,
    }));
  };



  if (loading) {
    return (
      <UserLayout>
        <div className="content-loading">加载中...</div>
      </UserLayout>
    );
  }

  return (
    <UserLayout>
      <div className="passkey-content">
        <div className="content-header">
          <h2 className="content-title">Passkey管理</h2>
        </div>
        
        {error && <div className="error-message">{error}</div>}
        {success && <div className="success-message">{success}</div>}

        <div className="passkey-section current-passkey">
          <h3 className="section-title">当前Passkey</h3>
          {currentPasskey ? (
            <div className="passkey-info-card">
              <div className="passkey-info">
                <div className="info-row">
                  <label>Passkey</label>
                  <div className="passkey-value">{currentPasskey.passkey}</div>
                </div>
                <div className="info-row">
                  <label>创建时间</label>
                  <div className="info-value">{new Date(currentPasskey.createdAt).toLocaleString()}</div>
                </div>
                <div className="info-row">
                  <label>下次可更换时间</label>
                  <div className="info-value">{new Date(currentPasskey.nextChangeAllowedAt).toLocaleString()}</div>
                </div>
              </div>
              <div className="passkey-actions">
                <button
                  onClick={handleGenerateNewPasskey}
                  className="generate-btn"
                  disabled={new Date(currentPasskey.nextChangeAllowedAt) > new Date()}
                >
                  生成新Passkey
                </button>
                {new Date(currentPasskey.nextChangeAllowedAt) > new Date() && (
                  <div className="warning-message">
                    距离下次可更换时间还有 {Math.ceil((new Date(currentPasskey.nextChangeAllowedAt) - new Date()) / (1000 * 60 * 60 * 24))} 天
                  </div>
                )}
              </div>
            </div>
          ) : (
            <div className="no-data-message">暂无Passkey</div>
          )}
        </div>

        <div className="passkey-section passkey-history">
          <h3 className="section-title">历史记录</h3>
          {passkeyHistory.length > 0 ? (
            <>
              <div className="table-container">
                <table className="passkey-table">
                  <thead>
                    <tr>
                      <th>Passkey</th>
                      <th>状态</th>
                      <th>创建时间</th>
                      <th>过期时间</th>
                    </tr>
                  </thead>
                  <tbody>
                    {passkeyHistory.map((record) => (
                      <tr key={record.passkeyId}>
                        <td>
                          <div className="passkey-value">{record.passkey}</div>
                        </td>
                        <td>
                          <span className={`status-badge ${record.isActive ? 'status-active' : 'status-inactive'}`}>
                            {record.isActive ? '活跃' : '已过期'}
                          </span>
                        </td>
                        <td>{new Date(record.createdAt).toLocaleString()}</td>
                        <td>
                          {record.expiredAt ? new Date(record.expiredAt).toLocaleString() : '-'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              
              <div className="pagination-container">
                <PaginationComponent
                  current={pagination.current}
                  pageSize={pagination.size}
                  total={pagination.total}
                  onChange={handlePageChange}
                />
              </div>
            </>
          ) : (
            <div className="no-data-message">暂无历史记录</div>
          )}
        </div>
      </div>
    </UserLayout>
  );
};

export default Passkey; 